package com.gipson.amc.service.basicdata;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsbj.common.msg.ResponseMessage;
import com.dsbj.starter.redis.utils.MultiRedisHelper;
import com.gipson.amc.entity.Application;
import com.gipson.amc.entity.PageByDataTable;
import com.gipson.amc.entity.User;
import com.gipson.amc.mapper.ApplicationMapper;
import com.gipson.amc.model.request.ClientTokenRequest;
import com.gipson.amc.utils.Constants;
import com.gipson.amc.utils.PasswordHelper;
import com.gipson.amc.utils.datagene.GeneUUID;
import com.gipson.amc.utils.security.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  应用系统 服务实现类
 * </p>
 *
 * @author xsyuan
 * @since 2020-05-09
 */
@Service
public class ApplicationService extends ServiceImpl<ApplicationMapper, Application> {

    @Autowired
    private MultiRedisHelper multiRedisHelper;


    public Page<Application> getApplicationPage(Application application, PageByDataTable pageByDataTable){
        Page<Application> page=new Page<Application>().setCurrent(pageByDataTable.getPageindex()).setSize(pageByDataTable.getPagesize());
        QueryWrapper<Application> queryWrapper=new QueryWrapper<Application>()
                .like(StringUtils.isNotBlank(application.getApplicationCode()),"APPLICATION_CODE",application.getApplicationCode())
                .like(StringUtils.isNotBlank(application.getApplicationName()),"APPLICATION_NAME",application.getApplicationName())
                .eq("DEL_FLAG",application.getDelFlag()==null?0:application.getDelFlag())
                .orderByAsc("SORT");
        baseMapper.selectPage(page,queryWrapper);
        return page;
    }

    /**
     * 删除
     * @param ids
     */
    public void delBatch(String ids){
        String[] idStr = ids.split(",");
        List<String> idList = Arrays.asList(idStr);
        List<Application> applicationList = baseMapper.selectBatchIds(idList);
        /*List<String> deleteByIds = new ArrayList<>();
        for (Application application : applicationList){
            deleteByIds.add(application.getId());
        }
        baseMapper.deleteBatchIds(deleteByIds);*/
        for (Application application : applicationList) {
            application.setDelFlag(1);
        }
        updateBatchById(applicationList, 1000);
    }

    @Transactional
    public ResponseMessage saveOrUpdateByApplication(Application application) {
        User user = ShiroUtils.getCurrentUser();
        if(user != null){
            if(StringUtils.isNotBlank(application.getId())){
                application.setUpdateUser(user.getId());
                application.setUpdateTime(new Date());
                updateById(application);
                return ResponseMessage.ok("修改成功");
            }else{
                List<Application> checkApplicationCode = list(Wrappers.<Application>lambdaQuery().eq(Application::getApplicationCode,application.getApplicationCode()));
                List<Application> checkApplicationName = list(Wrappers.<Application>lambdaQuery().eq(Application::getApplicationName,application.getApplicationName()));
                String msg = "";
                //判断系统编号是否重复
                if(CollectionUtils.isNotEmpty(checkApplicationCode)){
                    msg = "应用编号已存在！";
                    return ResponseMessage.error(msg);
                }
                //判断系统名称是否重复
                if(CollectionUtils.isNotEmpty(checkApplicationName)){
                    msg = "应用名称已存在！";
                    return ResponseMessage.error(msg);
                }
                application.setCreateUser(user.getId());
                application.setCreateTime(new Date());
                application.setPriKey(GeneUUID.getUUID());
                save(application);
                return ResponseMessage.ok("新增成功");
            }
        }
        return ResponseMessage.error("登陆用户不存在，请重新登陆！");
    }

    public ResponseMessage getClientToken(ClientTokenRequest clientTokenRequest) {
        QueryWrapper<Application> queryWrapper=new QueryWrapper<Application>()
                .eq("ID",clientTokenRequest.getAppId())
                .eq("DEL_FLAG",0);
        Application application = getOne(queryWrapper);
        if(application==null){
            return ResponseMessage.error(Constants.NETWORK_STATE_APP_NOT_EXIST,"应用不存在!");
        }
        String password = new SimpleHash("md5", clientTokenRequest.getAppId(), ByteSource.Util.bytes(application.getPriKey()), PasswordHelper.HASH_ITERATIONS).toHex();
        if(!password.equals(clientTokenRequest.getPriKey())){
            return ResponseMessage.error(Constants.NETWORK_STATE_INVALID_ACCESS,"口令错误!");
        }

        String clientToken = (String) multiRedisHelper.get(Constants.CLIENT_TOKEN_PREFIX+application.getId(),Constants.CLIENT_TOKEN_DATABASE);
        if(StringUtils.isEmpty(clientToken)){
            clientToken = GeneUUID.getUUID();
            multiRedisHelper.set(Constants.CLIENT_TOKEN_PREFIX+application.getId(),clientToken,Constants.EXPIRE_CLIENT_TOKEN,Constants.CLIENT_TOKEN_DATABASE);
        }

        return ResponseMessage.ok(clientToken);
    }

    /*****
     * 获取所有未删除的系统
     * @return
     */
    public List<Application> getAllApp(){
        List<Application> apps = list(Wrappers.<Application>lambdaQuery()
                .eq(Application::getDelFlag,0)
                .orderByAsc(Application::getSort)
        );
        return apps;
    }


    /**
     * 获取application列表。
     *
     * @param
     * @return
     * @author cjw 2020-05-12
     */
    public List<Application> getApplicationList() {
        Wrapper<Application> wrapper = Wrappers.<Application>lambdaQuery()
                .eq(Application::getDelFlag, 0)
                .orderByAsc(Application::getSort);
        List<Application> list_application = baseMapper.selectList(wrapper);
        return list_application;
    }

    /**
     * 根据applicationCode获取application。
     *
     * @param
     * @return
     * @author cjw 2020-05-12
     */
    public Application getApplicationByCode(String applicationCode) {
        Wrapper<Application> wrapper = Wrappers.<Application>lambdaQuery()
                .eq(Application::getApplicationCode, applicationCode)
                .eq(Application::getDelFlag, 0);
        Application application = baseMapper.selectOne(wrapper);
        return application;
    }


}
